#!/usr/bin/python
# -*- encoding: utf-8

import urllib, urllib2, re, xbmcplugin, xbmcgui
import webutils, commonutils
import CommonFunctions
import xbmcaddon

common = CommonFunctions
common.plugin = "TV Sme-1.0"

REMOTE_DBG = False

if REMOTE_DBG:
    from pysrc import pydevd as pydevd
    pydevd.settrace('localhost', stdoutToServer=True, stderrToServer=True)

def index():
    print "showIndex"
    
    text = webutils.tryGetTextFromUrl("http://tv.sme.sk/relacie/", "windows-1250")
    
    if text is None:
        commonutils.showError()
    else:                
        elements = common.parseDOM(text, "div", attrs={ "class" : "tv-show" })
        h2s = common.parseDOM(elements, "h2") #todo optimize
        urls = common.parseDOM(h2s, "a", ret="href")
        names = common.parseDOM(h2s, "a")
        
        #todo commonutils.addFolder("Najnovšie", "/hs/")
                        
        for url, name in zip(urls, names):
            commonutils.addFolder(name, url)
        
    print "showIndex done"
        
def subIndex(subUrl, fromPage):
    print "subIndex " + subUrl + " " + str(fromPage)
   
    settings = xbmcaddon.Addon(id="plugin.video.kolik-xbmc.sme")
    pageCount = int(settings.getSetting("pageCount"))
    
    for pageNo in range(fromPage, fromPage + pageCount - 1):
        text = webutils.tryGetTextFromUrl("http://tv.sme.sk" + subUrl + "?st=" + str(pageNo), "windows-1250")        
        
        if text is None:
            commonutils.addErrorText()
        else:           
            items = common.parseDOM(text, "div", attrs={ "class" : "item" })
            videoitems = common.parseDOM(text, "div", attrs={ "class" : "txt" })
            videoimages = common.parseDOM(items, "img", ret="src")            
            videourls = common.parseDOM(videoitems, "a", ret="href")
            videonames = common.parseDOM(videoitems, "a")
            videoplots = common.parseDOM(videoitems, "p")
                             
            for url, name, image, plot in zip(videourls, videonames, videoimages, videoplots):
                videoId = re.search("[0-9]+", url).group(0)
                commonutils.addLink(name, videoId, image, plot, subUrl)
           
                
    commonutils.addFolder("Ďalšie...", subUrl, fromPage + pageCount)
    print "subIndex done"

def playVideo(id):
    print "playVideo", id
    dialog = xbmcgui.DialogProgress()
    dialog.create('TV Sme', 'Zisťuje sa umiestnenie videa...')
    
    url = 'http://www.sme.sk/storm/mmdata_get.asp?id=' + str(id) + '&rev=4&small=0&podcast=0'
    
    text = webutils.tryGetTextFromUrl(url)
    
    if dialog.iscanceled():
        return
    
    if text is None:
        commonutils.showError()
    else:
        videoUrl = re.search("<location>(.*?)</location>", text).group(1)
        title = re.search("<title>(.*?)</title>", text).group(1)
        image = re.search("<image>(.*?)</image>", text).group(1)
        
        item = xbmcgui.ListItem(label = title, iconImage = image, thumbnailImage = image, path = videoUrl)
        item.setInfo(type='Video', infoLabels = { "Title" : title })
        
        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded = True, listitem = item)
           
    print "playVideo done"


params = commonutils.getParams()

videoId = commonutils.tryGetIntParam(params, "id")
subUrl = commonutils.tryGetStrParam(params, "sub")
fromPage = commonutils.tryGetIntParam(params, "page", 1)
   
if videoId is not None:
    playVideo(videoId)
elif subUrl is not None:
    subIndex(subUrl, fromPage)
else:
    index()  

xbmcplugin.endOfDirectory(int(sys.argv[1]))
